package Server.impl;

import BaseQuery.BaseQuery;
import Bean.User;
import Dao.IUserDao;
import Dao.impl.UserDao;
import Server.IUserServe;
import vo.PageBean;
import vo.ResultBean;

import java.util.List;

public class UserService implements IUserServe {

    private IUserDao userDao;
    public UserService(){
        userDao = new UserDao();
    }
    @Override
    public ResultBean add(User user) throws Exception {
        if(user == null || user.getUserName() == null){
            return ResultBean.ERROR(1001,"params is null");
        }
        int add = userDao.add(user);
        return add>0?ResultBean.SUCCESS(user):ResultBean.ERROR("add is failed");
    }

    @Override
    public ResultBean update(User user) throws Exception {
        if(user == null || user.getUserName() == null
        || user.getUserId() == null){
            return ResultBean.ERROR(1001,"params is null");
        }
        int update = userDao.update(user);
        return update>0?ResultBean.SUCCESS(user):ResultBean.ERROR("update is failed");
    }

    @Override
    public ResultBean delete(Integer id) throws Exception {
        if(id == null){
            return ResultBean.ERROR(1001,"params is null");
        }
        int delete = userDao.delete(id);
        return delete>0?ResultBean.SUCCESS():ResultBean.ERROR("delete is failed");
    }


    @Override
    public ResultBean getById(Integer id) throws Exception {
        if(id == null){
            return ResultBean.ERROR(1001,"params is null");
        }
         User user = userDao.getById(id);
        return user!=null?ResultBean.SUCCESS(user):ResultBean.ERROR("get user by id is failed");
    }

    @Override
    public ResultBean getAll() throws Exception {
        List<User> userList = userDao.getAll();
        return userList!=null?ResultBean.SUCCESS(userList):ResultBean.ERROR("get user is failed");
    }

    @Override
    public ResultBean getByPage(BaseQuery baseQuery) throws Exception {

        if(baseQuery == null){
            baseQuery = new BaseQuery();
        }
        PageBean<User> pageBean = new PageBean<>();

        int count = userDao.getCount(baseQuery);
        pageBean.setTotalRows(count);
        if(count%baseQuery.getPageCount()==0){
            pageBean.setTotalPages(count/baseQuery.getPageCount());
        }else{
            pageBean.setTotalPages(count/baseQuery.getPageCount()+1);
        }

        List<User> userList = userDao.getByPage(baseQuery);
        pageBean.setData(userList);

        return ResultBean.SUCCESS(pageBean);
    }
    @Override
    public ResultBean batchDel(List<Integer> ids) throws Exception {
        if(ids==null|| ids.size()==0) {
            return ResultBean.ERROR("params is null");
        }
        for(Integer id:ids) {
            userDao.delete(id);
        }
        return ResultBean.SUCCESS();
    }
}
